package com.boarsoft.boar.config.apollo.plugin;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.boarsoft.boar.config.apollo.listener.ApolloConfigChangeListener;
import com.boarsoft.config.core.ConfigFileListener;
import com.boarsoft.config.core.ConfigFileSyncImpl;
import com.boarsoft.config.manager.PropConfigManager;
import com.boarsoft.config.plugin.ConfigPlugin;
import com.boarsoft.config.spring.util.SpringContextUtil;
import com.boarsoft.config.util.ConfigUtils;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;

/**
 * 基于apollo-client封装的扩展插件
 *
 */
public class ApolloPlugin implements ConfigPlugin {

	private ConfigFileSyncImpl configFileSync;

	@Override
	public void init() {
		this.configFileSync = SpringContextUtil.getBean(ConfigFileSyncImpl.class);
		initPropConfig();
		initFileConfig();
	}

	public void initPropConfig() {
		ConcurrentHashMap<String, Object> configMap = PropConfigManager.getAllResource();
		for (String resourceId : configMap.keySet()) {
			String namespace = resourceId.substring(resourceId.lastIndexOf(".") + 1);
			Config config = ConfigService.getConfig(namespace);
			config.addChangeListener(new ApolloConfigChangeListener());
			Map<String, Object> param = new HashMap<>();
			for (String key : config.getPropertyNames()) {
				param.put(key, config.getProperty(key, null));
			}
			try {
				ConfigUtils.setProperties(configMap.get(resourceId), param);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}

	public void initFileConfig() {
		for (String namespace : configFileSync.getFileConfigMap().keySet()) {
			String fp = configFileSync.getFileConfigMap().get(namespace);
			try {
				String content = ConfigService.getConfigFile(namespace,
						ConfigFileFormat.fromString(fp.substring(fp.lastIndexOf(".") + 1).toUpperCase())).getContent();
				if (content == null) {
					continue;
				}
				configFileSync.save(fp, content.getBytes(StandardCharsets.UTF_8));
				ConfigFileListener configListener = configFileSync.getConfigListener(namespace);
				if (configListener != null) {
					configListener.onReady(fp);
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}

	@Override
	public void refresh() {
	}
}
